<template>
  <view class="ad-form-page">
    <view class="header">
      <text class="title">{{ isEdit ? '编辑广告' : '添加广告' }}</text>
    </view>
    
    <form @submit="handleSubmit">
      <view class="form-section">
        <view class="form-item">
          <text class="label">广告标题 *</text>
          <input 
            v-model="form.title" 
            class="input" 
            placeholder="请输入广告标题"
            maxlength="50"
          />
        </view>
        
        <view class="form-item">
          <text class="label">广告描述 *</text>
          <textarea 
            v-model="form.description" 
            class="textarea" 
            placeholder="请输入广告描述"
            maxlength="200"
          ></textarea>
        </view>
        
        <view class="form-item">
          <text class="label">广告图片 *</text>
          <view class="image-upload">
            <image 
              v-if="form.imageUrl" 
              :src="form.imageUrl" 
              class="preview-image"
              @click="previewImage"
            ></image>
            <view v-else class="upload-placeholder" @click="chooseImage">
              <text>点击上传图片</text>
            </view>
            <button v-if="form.imageUrl" class="change-btn" @click="chooseImage">
              更换图片
            </button>
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">目标链接 *</text>
          <input 
            v-model="form.targetUrl" 
            class="input" 
            placeholder="请输入目标链接"
          />
        </view>
        
        <view class="form-item">
          <text class="label">广告位置 *</text>
          <picker :value="positionIndex" :range="positionOptions" @change="onPositionChange">
            <view class="picker">
              {{ positionOptions[positionIndex] }}
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">优先级</text>
          <input 
            v-model.number="form.priority" 
            class="input" 
            type="number"
            placeholder="数字越大优先级越高"
          />
        </view>
        
        <view class="form-item">
          <text class="label">开始时间 *</text>
          <picker 
            mode="date" 
            :value="form.startDate" 
            @change="onStartDateChange"
          >
            <view class="picker">
              {{ form.startDate || '请选择开始时间' }}
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">结束时间 *</text>
          <picker 
            mode="date" 
            :value="form.endDate" 
            @change="onEndDateChange"
          >
            <view class="picker">
              {{ form.endDate || '请选择结束时间' }}
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <view class="switch-item">
            <text class="label">是否启用</text>
            <switch :checked="form.isActive" @change="onSwitchChange" />
          </view>
        </view>
      </view>
      
      <view class="form-actions">
        <button class="cancel-btn" @click="goBack">取消</button>
        <button class="submit-btn" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </button>
      </view>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEdit: false,
      adId: null,
      form: {
        title: '',
        description: '',
        imageUrl: '',
        targetUrl: '',
        position: 'banner',
        priority: 0,
        startDate: '',
        endDate: '',
        isActive: true
      },
      positionIndex: 0,
      positionOptions: ['横幅', '侧边栏', '弹窗', '页脚'],
      positionMap: ['banner', 'sidebar', 'popup', 'footer']
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.isEdit = true
      this.adId = options.id
      this.loadAdData()
    }
  },
  
  methods: {
    async loadAdData() {
      try {
        const res = await this.$api.get(`/ads/${this.adId}`)
        const ad = res.data.data
        
        this.form = {
          title: ad.title,
          description: ad.description,
          imageUrl: ad.imageUrl,
          targetUrl: ad.targetUrl,
          position: ad.position,
          priority: ad.priority,
          startDate: ad.startDate.split('T')[0],
          endDate: ad.endDate.split('T')[0],
          isActive: ad.isActive
        }
        
        this.positionIndex = this.positionMap.indexOf(ad.position)
      } catch (error) {
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },
    
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })
        
        const tempFilePath = res.tempFilePaths[0]
        
        // 上传图片
        const uploadRes = await uni.uploadFile({
          url: this.$api.defaults.baseURL + '/files/upload',
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          }
        })
        
        const result = JSON.parse(uploadRes.data)
        if (result.success) {
          this.form.imageUrl = result.data.url
        } else {
          throw new Error(result.message)
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      }
    },
    
    previewImage() {
      uni.previewImage({
        urls: [this.form.imageUrl]
      })
    },
    
    onPositionChange(e) {
      this.positionIndex = e.detail.value
      this.form.position = this.positionMap[this.positionIndex]
    },
    
    onStartDateChange(e) {
      this.form.startDate = e.detail.value
    },
    
    onEndDateChange(e) {
    onEndDateChange(e) {
      this.form.endDate = e.detail.value
    },
    
    onSwitchChange(e) {
      this.form.isActive = e.detail.value
    },
    
    validateForm() {
      if (!this.form.title.trim()) {
        uni.showToast({
          title: '请输入广告标题',
          icon: 'none'
        })
        return false
      }
      
      if (!this.form.description.trim()) {
        uni.showToast({
          title: '请输入广告描述',
          icon: 'none'
        })
        return false
      }
      
      if (!this.form.imageUrl) {
        uni.showToast({
          title: '请上传广告图片',
          icon: 'none'
        })
        return false
      }
      
      if (!this.form.targetUrl.trim()) {
        uni.showToast({
          title: '请输入目标链接',
          icon: 'none'
        })
        return false
      }
      
      if (!this.form.startDate) {
        uni.showToast({
          title: '请选择开始时间',
          icon: 'none'
        })
        return false
      }
      
      if (!this.form.endDate) {
        uni.showToast({
          title: '请选择结束时间',
          icon: 'none'
        })
        return false
      }
      
      if (new Date(this.form.endDate) <= new Date(this.form.startDate)) {
        uni.showToast({
          title: '结束时间必须晚于开始时间',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    async handleSubmit() {
      if (!this.validateForm()) return
      
      try {
        const data = { ...this.form }
        
        if (this.isEdit) {
          await this.$api.put(`/ads/${this.adId}`, data)
          uni.showToast({
            title: '更新成功'
          })
        } else {
          await this.$api.post('/ads', data)
          uni.showToast({
            title: '创建成功'
          })
        }
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.ad-form-page {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.form-section {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.input, .textarea, .picker {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fafafa;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.picker {
  color: #333;
}

.image-upload {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.preview-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
}

.upload-placeholder {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 24rpx;
}

.change-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 16rpx 32rpx;
  font-size: 24rpx;
  width: 200rpx;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-actions {
  display: flex;
  gap: 20rpx;
}

.cancel-btn, .submit-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.submit-btn {
  background: #007aff;
  color: white;
}
</style>